import { useEffect } from "react"
import { isSameElement } from "../utils"
type TriggerType = 'click' | 'dblclick' | 'touchmove' | 'touchstart' | 'touchend'

/**
 * 检测是否在指定元素外触发的事件
 *  @param cb 回调函数
 * @param triggerType 触发事件类型
 * @param targetSelector 判断的目标元素
 * @param excludeSelector 可选 拍粗的选择器
 */
function useTriggerOutset (cb: Function, triggerType: TriggerType, targetSelector: string | string[], excludeSelector?: string | string[]) {
    useEffect(() => {
        if(!Array.isArray(targetSelector)) {
            targetSelector = [targetSelector]
        }
        // 二维函数
        const targets = targetSelector.map(one => document.querySelectorAll(one)).filter(one => !!one).map(one => Array.from(one))
        if(!Array.isArray(excludeSelector)) {
             // @ts-ignore
            excludeSelector = [excludeSelector]
        }
        // @ts-ignore
        const excludes = excludeSelector.map(one => document.querySelectorAll(one)).filter(one => !!one).map(one => Array.from(one))
        const handler = (event: Event) => {
            // @ts-ignore
            const excludeResult = excludes.some(item => item.some(one => isSameElement(one, event.target as any)))
            if (excludeResult) return false
            const result = targets.some(item => item.some(one => isSameElement(one, event.target as any)))
            if(result) return false
            cb(event)
        }
        document.addEventListener(triggerType, handler)
        return function () {
            document.removeEventListener(triggerType, handler)
        }
    }, [triggerType, targetSelector, cb])
}

export default useTriggerOutset